use std::{
    fs,
    path::Path,
    error::Error,
};
use serde::Deserialize;

pub fn create_path(path: &str) {
    let path = Path::new(path);
    if !path.exists() {
        fs::create_dir_all(path).unwrap();
    }
}

pub struct YamlUtil;

impl YamlUtil {
    pub fn read<T>(path: &'static str) -> Result<T, Box<dyn Error>>
        where T: for<'de> Deserialize<'de>
    {
        let s = fs::read_to_string(path)?;
        let t = serde_yaml::from_str::<T>(&s)?;
        Ok(t)
    }
}

#[cfg(test)]
mod tests {
    use serde_derive::Deserialize;

    #[derive(Debug, Deserialize)]
    struct Yaml {
        test: Opt,
    }

    #[derive(Debug, Deserialize)]
    struct Opt {
        my: Info,
        or: Info,
    }

    #[derive(Debug, Deserialize)]
    struct Info {
        name: String,
        id: usize,
    }

    #[test]
    fn test_read() {
        use crate::basic::util::file::YamlUtil;
        //test:
        //   my:
        //     name: squbirreland
        //     id: 10
        //   or:
        //     name: some
        //     id: 0
        let yaml = YamlUtil::read::<Yaml>("tmp/tmp.yml").unwrap();
        println!("{:?}", yaml);
    }
}